﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using System.Threading.Tasks;
using Sustainalytics.OS;

namespace Sustainalytics.ESGComputing.Launcher
{
    partial class ESGLauncherService : ServiceBase
    {
        private string _childProcessToRun;
        public ESGLauncherService(string cmd)
        {
            _childProcessToRun = cmd;
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            Task t = Task.Factory.StartNew(() =>
            {
                try
                {
                    string cmd = _childProcessToRun;
                    EventLog.WriteEntry(string.Format("Starting process:  {0} ...", cmd), EventLogEntryType.Information);
                    var process = LinkedProcess.Start(cmd, true, true);
                    process.WaitForExit();
                    this.ExitCode = 0;
                    this.Stop();
                }
                catch (Win32Exception e)
                {
                    EventLog.WriteEntry(string.Format("error: {0}", e.Message), EventLogEntryType.Warning);
                    this.ExitCode = e.ErrorCode;
                    
                }
                catch (Exception e)
                {
                    EventLog.WriteEntry(string.Format("error: {0}", e.Message), EventLogEntryType.Warning);
                    this.ExitCode = -1;
                }

                this.Stop();
            });
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
        }

       
    }
}
